//
//  ProductDetailViewController.m
//  Peso Guide
//
//  Created by macbook on 2025/6/10.
//

#import "ProductDetailViewController.h"
#import "ProductDetailView.h"
#import "ProductDetailCell.h"
#import "CustomWebViewController.h"
#import "IdentityInfomationVC.h"
#import "IdentityUserJobInfoVC.h"
#import "BindCardInfoVC.h"
#import "IdentityContactInfoVC.h"
#import "IdentityUserInfoVC.h"
#import "MineSettingViewController.h"
#import "MJRefresh/MJRefresh.h"
#import "IDCardFaceIDVC.h"

@interface ProductDetailViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) BaseTableView *tableView;
@property (nonatomic, strong) NSDictionary *headerDic;
@property (nonatomic, strong) NSMutableArray *cellArray;
@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) UIView *agreeView;
@property (nonatomic, strong) UIButton *chooseButton;
@property (nonatomic, strong) UIButton *loanButton;
@property (nonatomic, strong) NSDictionary *yes;
@property (nonatomic, strong) UILabel *agreementButton;

@property (nonatomic, strong) NSString *lat;
@property (nonatomic, strong) NSString *lng;

@end

@implementation ProductDetailViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self loadRequest];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [[LocationManager sharedManager] getCurrentLocationWithSuccess:^(CLLocationCoordinate2D coordinate) {
            DLog(@"get location success：log=%f, lat=%f", coordinate.longitude, coordinate.latitude);
            
            self.lng = [NSString stringWithFormat:@"%f",coordinate.longitude];
            self.lat = [NSString stringWithFormat:@"%f",coordinate.latitude];

            // 使用获取到的经纬度做其他操作...
            
        } failure:^(NSError *error) {
            // 处理错误情况...
        }];
    
    self.titleLabel.text = @"";
    self.navView.backgroundColor = ColorHex(@"#1A7A35");
    self.backColor = ColorHex(@"#1A7A35");
    [self.backButton setBackgroundImage:[UIImage imageNamed:@"ic_backBtn_white"] forState:0];

    [self.view addSubview:self.tableView];
    
    WeakSelf;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf loadRequest];
    }];
    
    _bottomView = [PesoKit createViewWithFrame:CGRectMake(0, self.tableView.bottom, KScreenWidth, 100+kSafeBottomHeight) backGroundColor:ColorHex(@"#FFFFFF")];
    [self.view addSubview:_bottomView];
    
    _agreeView = [PesoKit createViewWithFrame:CGRectMake(0, 0, KScreenWidth, 17) backGroundColor:[UIColor clearColor]];
    [_bottomView addSubview:_agreeView];
    
    NSMutableAttributedString *rmbStr = [[NSMutableAttributedString alloc] initWithString:[Lang set:@"I have read and agree with <Privacy agreement>"] attributes:nil];
    NSRange rangeRmb=[[Lang set:@"I have read and agree with <Privacy agreement>"] rangeOfString:[NSString stringWithFormat:@"%@", [Lang set:@"<Privacy agreement>"]]];
    NSDictionary *fontDic=[NSDictionary dictionaryWithObjectsAndKeys:[UIColor colorWithHexString:@"#1A7A35"],NSForegroundColorAttributeName,FONT(FontWeightStyleRegular, 12),NSFontAttributeName, nil];
    [rmbStr addAttributes:fontDic range:rangeRmb];

    
    _agreementButton = [PesoKit createLabelWithFrame:CGRectMake(42+15+5, 0, KScreenWidth-64, 17) backGroundColor:[UIColor clearColor] text:[Lang set:@"I have read and agree with <Privacy agreement>"] textColor:ColorHex(@"#0E1D31") font:FONT(FontWeightStyleRegular, 12)];
    _agreementButton.attributedText = rmbStr;
    _agreementButton.userInteractionEnabled = YES;
    _agreementButton.numberOfLines = 3;
    [_agreementButton sizeToFit];
    [_agreeView addSubview:_agreementButton];
    
    CGSize agreeSize = [AppTools sizeWithText:_agreementButton.text font:FONT(FontWeightStyleRegular, 12) maxSize:CGSizeMake(KScreenWidth-64, 100)];
    _agreementButton.height = ceil(agreeSize.height+10);
    _agreeView.height = ceil(agreeSize.height+10);
    _agreeView.top = 0;
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(agreementButtonClick)];
    [_agreementButton addGestureRecognizer:tapGesture];
    
    _chooseButton = [[UIButton alloc] initWithFrame:CGRectMake(42, (ceil(agreeSize.height+10)-15)/2.0, 15, 15)];
    [_chooseButton setBackgroundImage:[UIImage imageNamed:@"ic_login_agree_select"] forState:0];
    _chooseButton.selected = YES;
    [_chooseButton addTarget:self action:@selector(chooseButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [_bottomView addSubview:_chooseButton];
    
    _loanButton = [PesoKit createButtonWithFrame:CGRectMake((KScreenWidth-214)/2.0, _chooseButton.bottom+17, 214, 44) backGroundColor:ColorHex(@"#D8D8D8") title:@"" titleColor:ColorHex(@"#FFFFFF") font:FONT(FontWeightStyleMedium, 18)];
    _loanButton.userInteractionEnabled = NO;
    _loanButton.clipsToBounds = YES;
    _loanButton.layer.cornerRadius = 22.0f;
    [_loanButton addTarget:self action:@selector(loanButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [_bottomView addSubview:_loanButton];
    
    self.agreeView.hidden = YES;
    self.chooseButton.hidden = YES;
}

- (void)loadRequest {
    [[AWHttpService service] postWithUrl:@"/trains/import" params:@{@"across":self.productId} succ:^(id  _Nonnull responseObject) {
        if (SUCCESS) {
            NSDictionary *associating = [NSDictionary safeDictionaryWithDictionary:[responseObject safeObjectForKey:@"associating"]];
            self.headerDic = [NSDictionary safeDictionaryWithDictionary:[associating safeObjectForKey:@"handled"]];
            self.cellArray = [NSMutableArray arrayWithArray:[associating safeObjectForKey:@"combine"]];
            NSString *allowed = [NSString stringWithFormat:@"%@",[self.headerDic safeObjectForKey:@"allowed"]];
            NSString *assigning = [NSString stringWithFormat:@"%@",[self.headerDic safeObjectForKey:@"assigning"]];

            self.titleLabel.text = allowed;
            
            BOOL isAllClear = YES;
            for (NSDictionary *dataDic in self.cellArray) {
                NSString *packages = [NSString stringWithFormat:@"%@",[dataDic safeObjectForKey:@"packages"]];
                if (![packages isEqualToString:@"1"]) {
                    isAllClear = NO;
                    break;
                }
            }
            [self.loanButton setTitle:assigning forState:0];
            
            if (isAllClear == NO) {
                self.loanButton.userInteractionEnabled = NO;
            }else {
                self.loanButton.userInteractionEnabled = YES;
                self.loanButton.backgroundColor = ColorHex(@"#FE7133");
            }
            
            self.yes = [NSDictionary safeDictionaryWithDictionary:[associating safeObjectForKey:@"yes"]];
            NSString *accidental = [NSString stringWithFormat:@"%@",[self.yes safeObjectForKey:@"accidental"]];
            if ([AppTools isEmpty:accidental]) {
                self.agreeView.hidden = YES;
                self.chooseButton.hidden = YES;
            }else {
                self.agreeView.hidden = NO;
                self.chooseButton.hidden = NO;
                
                NSArray *accidentalArr = [accidental componentsSeparatedByString:@"||"];
                if (accidentalArr.count > 0) {
                    NSString *string1 = [accidentalArr safeObjectAtIndex:0];
                    NSString *string2 = [accidentalArr safeObjectAtIndex:1];
                    NSString *allString = [NSString stringWithFormat:@"%@%@",string1,string2];

                    NSMutableAttributedString *rmbStr = [[NSMutableAttributedString alloc] initWithString:allString attributes:nil];
                    NSRange rangeRmb=[allString rangeOfString:string2];
                    NSDictionary *fontDic=[NSDictionary dictionaryWithObjectsAndKeys:[UIColor colorWithHexString:@"#1A7A35"],NSForegroundColorAttributeName,FONT(FontWeightStyleRegular, 12),NSFontAttributeName, nil];
                    [rmbStr addAttributes:fontDic range:rangeRmb];

                    self.agreementButton.attributedText = rmbStr;

                    CGSize agreeSize = [AppTools sizeWithText:self.agreementButton.text font:FONT(FontWeightStyleRegular, 12) maxSize:CGSizeMake(KScreenWidth-64, 100)];
                    self.agreementButton.height = ceil(agreeSize.height+10);
                    self.agreeView.height = ceil(agreeSize.height+10);
                    self.agreeView.top = 0;
                }else {
                    self.agreementButton.text = accidental;
                }
            }
            
            [self.tableView reloadData];
            [self.tableView.mj_header endRefreshing];
            
        }else {
            [self.tableView.mj_header endRefreshing];
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",[responseObject safeObjectForKey:@"order"]]];
            [SVProgressHUD dismissWithDelay:3.0f];

        }
    } fail:^(NSInteger errorType, id  _Nonnull error) {}];
}

- (void)loanButtonClick {
    if (_chooseButton.isSelected == NO) {
        [SVProgressHUD showErrorWithStatus:[Lang set:@"Please agree to the privacy policy"]];
        [SVProgressHUD dismissWithDelay:3.0f];

        return;
    }
    
    NSString *returning = [NSString stringWithFormat:@"%@",[self.headerDic safeObjectForKey:@"returning"]];
    NSString *lifetimes = [NSString stringWithFormat:@"%@",[self.headerDic safeObjectForKey:@"lifetimes"]];
    NSString *meld = [NSString stringWithFormat:@"%@",[self.headerDic safeObjectForKey:@"meld"]];
    NSString *optionally = [NSString stringWithFormat:@"%@",[self.headerDic safeObjectForKey:@"optionally"]];

    NSDictionary *params = @{@"sense":lifetimes,@"returning":returning,@"optionally":optionally,@"meld":meld};
    [[AWHttpService service] postWithUrl:@"/trains/my_env" params:params succ:^(id  _Nonnull responseObject) {
        if (SUCCESS) {
            NSString *time = [DataPointManager getCurrentTimestamp];
            
            if (![AppTools isEmpty:self.lat] && ![AppTools isEmpty:self.lng]) {
                [[DataPointManager sharedManager] senRequestWithType:@"9" startTime:time endTime:time lng:self.lng lat:self.lat orderId:lifetimes];
            }else {
                [[LocationManager sharedManager] getCurrentLocationWithSuccess:^(CLLocationCoordinate2D coordinate) {
                    DLog(@"get location success：log=%f, lat=%f", coordinate.longitude, coordinate.latitude);
                    
                    NSString *lng = [NSString stringWithFormat:@"%f",coordinate.longitude];
                    NSString *lat = [NSString stringWithFormat:@"%f",coordinate.latitude];
                    
                    [[DataPointManager sharedManager] senRequestWithType:@"9" startTime:time endTime:time lng:lng lat:lat orderId:lifetimes];

    //                [[DataPointManager sharedManager] logEventWithType:@"9" startTime:time endTime:time orderId:lifetimes];

                    // 使用获取到的经纬度做其他操作...
                    
                } failure:^(NSError *error) {
                    // 处理错误情况...
                }];
            }
            
            NSDictionary *associating = [NSDictionary safeDictionaryWithDictionary:[responseObject safeObjectForKey:@"associating"]];
            NSString *recent = [NSString stringWithFormat:@"%@",[associating safeObjectForKey:@"recent"]];
            
            if ([recent rangeOfString:@"http://"].location != NSNotFound ||
                [recent rangeOfString:@"https://"].location != NSNotFound) {
                //webView
                CustomWebViewController *webVC = [[CustomWebViewController alloc] init];
                webVC.linkUrl = recent;
                webVC.backRoot = YES;
                [[AppTools getCurrentVC].navigationController pushViewController:webVC animated:YES];
                return;
            }
            if ([recent rangeOfString:@"pe://so.gui.de/thelike"].location != NSNotFound) {
                //设置
                MineSettingViewController *settingVC = [[MineSettingViewController alloc] init];
                settingVC.hidesBottomBarWhenPushed = YES;
                [[AppTools getCurrentVC].navigationController pushViewController:settingVC animated:YES];
                return;
                return;
            }
            if ([recent rangeOfString:@"pe://so.gui.de/andlove"].location != NSNotFound) {
                //首页
                [AppTools getCurrentVC].tabBarController.selectedIndex = 0;
                return;
            }
            if ([recent rangeOfString:@"pe://so.gui.de/standard"].location != NSNotFound) {
                //登录
                [AppTools toLogin];
                return;
            }
            if ([recent rangeOfString:@"pe://so.gui.de/classes"].location != NSNotFound) {
                //订单
                [AppTools getCurrentVC].tabBarController.selectedIndex = 1;
                return;
            }
            if ([recent rangeOfString:@"pe://so.gui.de/islove"].location != NSNotFound) {
                //产品详情
                NSArray *array = [recent componentsSeparatedByString:@"="];
                NSString *theId = [NSString stringWithFormat:@"%@",[array safeObjectAtIndex:1]];
                ProductDetailViewController *vc = [[ProductDetailViewController alloc] init];
                vc.productId = theId;
                vc.hidesBottomBarWhenPushed = YES;
                [[AppTools getCurrentVC].navigationController pushViewController:vc animated:YES];
                return;
            }
            
        }
    } fail:^(NSInteger errorType, id  _Nonnull error) {
        
    }];
}

- (void)agreementButtonClick {
    //查看协议
    NSString *accidental = [NSString stringWithFormat:@"%@",[self.yes safeObjectForKey:@"narrower"]];

    CustomWebViewController *webVC = [[CustomWebViewController alloc] init];
    webVC.linkUrl = accidental;
    [self.navigationController pushViewController:webVC animated:YES];
}

- (void)chooseButtonClick:(UIButton *)sender {
    if (sender.isSelected == NO) {
        sender.selected = YES;
        [_chooseButton setBackgroundImage:[UIImage imageNamed:@"ic_login_agree_select"] forState:0];
    }else {
        sender.selected = NO;
        [_chooseButton setBackgroundImage:[UIImage imageNamed:@"ic_login_agree"] forState:0];
    }
}

#pragma mark - UITableViewDelegate&UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.cellArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *ProductDetailCellIdentifier = [NSString stringWithFormat:@"ProductDetailCellIdentifier%ld",(long)indexPath.row];
    ProductDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:ProductDetailCellIdentifier];
    if (!cell) {
        cell = [[ProductDetailCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ProductDetailCellIdentifier];
    }
    if (self.cellArray.count > 0) {
        cell.theIndex = indexPath.row;
        cell.dataDic = [self.cellArray safeObjectAtIndex:indexPath.row];
    }
    return cell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        return 114;
    }else {
        return 64;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    ProductDetailView *headerView = [[ProductDetailView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 165)];
    if (![AppTools isEmpty:self.headerDic]) {
        headerView.dataDic = self.headerDic;
    }
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 165;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *dataDic = [self.cellArray safeObjectAtIndex:indexPath.row];
    NSString *almost = [NSString stringWithFormat:@"%@",[dataDic safeObjectForKey:@"almost"]];
    if ([almost isEqualToString:@"namelovea"]) {
        NSString *packages = [NSString stringWithFormat:@"%@",[dataDic safeObjectForKey:@"packages"]];
        if ([packages isEqualToString:@"1"]) {
            //人脸身份认证不能修改
            
            IDCardFaceIDVC *vc = [[IDCardFaceIDVC alloc] init];
            vc.productId = self.productId;
            [self.navigationController pushViewController:vc animated:YES];
            
            return;
        }
    }
    
    for (int i = 0; i < self.cellArray.count; i++) {
        NSDictionary *cellDic = [self.cellArray safeObjectAtIndex:i];
        NSString *cellPackages = [NSString stringWithFormat:@"%@",[cellDic safeObjectForKey:@"packages"]];
        if (indexPath.row == i && cellPackages.integerValue == 1) {
            NSString *cellAlmost = [NSString stringWithFormat:@"%@",[cellDic safeObjectForKey:@"almost"]];
            [self pushIDentity:cellAlmost dataDic:dataDic];
            break;
        }else {
            if ([cellPackages isEqualToString:@"0"]) {
                NSString *cellAlmost = [NSString stringWithFormat:@"%@",[cellDic safeObjectForKey:@"almost"]];
                [self pushIDentity:cellAlmost dataDic:dataDic];
                break;
            }
        }
    }
}

- (void)pushIDentity:(NSString *)almost dataDic:(NSDictionary *)dataDic {
    if ([almost isEqualToString:@"namelovea"]) {
        // ocr认证
        NSString *startTime = [DataPointManager getCurrentTimestamp];
        [[NSUserDefaults standardUserDefaults] setObject:startTime forKey:@"upLogType-2-startTime"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        [[LocationManager sharedManager] getCurrentLocationWithSuccess:^(CLLocationCoordinate2D coordinate) {
            DLog(@"get location success：log=%f, lat=%f", coordinate.longitude, coordinate.latitude);
            
            NSString *lng = [NSString stringWithFormat:@"%f",coordinate.longitude];
            NSString *lat = [NSString stringWithFormat:@"%f",coordinate.latitude];

            [[NSUserDefaults standardUserDefaults] setObject:lng forKey:@"upLogType-2-lng"];
            [[NSUserDefaults standardUserDefaults] setObject:lat forKey:@"upLogType-2-lat"];
            [[NSUserDefaults standardUserDefaults] synchronize];

            // 使用获取到的经纬度做其他操作...
            
        } failure:^(NSError *error) {
            // 处理错误情况...
        }];
        
        IDCardFaceIDVC *vc = [[IDCardFaceIDVC alloc] init];
        vc.productId = self.productId;
        [self.navigationController pushViewController:vc animated:YES];
    }
    if ([almost isEqualToString:@"nameloveb"]) {
        // 个人信息
        IdentityUserInfoVC *vc = [[IdentityUserInfoVC alloc] init];
        vc.productId = self.productId;
        [self.navigationController pushViewController:vc animated:YES];
    }
    if ([almost isEqualToString:@"namelovec"]) {
        // 个人信息-工作
        IdentityUserJobInfoVC *vc = [[IdentityUserJobInfoVC alloc] init];
        vc.productId = self.productId;
        [self.navigationController pushViewController:vc animated:YES];
    }
    if ([almost isEqualToString:@"nameloved"]) {
        // 紧急联系人
        IdentityContactInfoVC *vc = [[IdentityContactInfoVC alloc] init];
        vc.productId = self.productId;
        [self.navigationController pushViewController:vc animated:YES];
    }
    if ([almost isEqualToString:@"namelovee"]) {
        // 绑卡
        NSString *recent = [NSString stringWithFormat:@"%@",[dataDic safeObjectForKey:@"recent"]];
        
        if ([recent rangeOfString:@"http://"].location != NSNotFound ||
            [recent rangeOfString:@"https://"].location != NSNotFound) {
            //webView
            CustomWebViewController *webVC = [[CustomWebViewController alloc] init];
            webVC.linkUrl = recent;
            [[AppTools getCurrentVC].navigationController pushViewController:webVC animated:YES];
            return;
        }
        if ([recent rangeOfString:@"pe://so.gui.de/thelike"].location != NSNotFound) {
            //设置
            MineSettingViewController *settingVC = [[MineSettingViewController alloc] init];
            settingVC.hidesBottomBarWhenPushed = YES;
            [[AppTools getCurrentVC].navigationController pushViewController:settingVC animated:YES];
            return;
            return;
        }
        if ([recent rangeOfString:@"pe://so.gui.de/andlove"].location != NSNotFound) {
            //首页
            [AppTools getCurrentVC].tabBarController.selectedIndex = 0;
            return;
        }
        if ([recent rangeOfString:@"pe://so.gui.de/standard"].location != NSNotFound) {
            //登录
            [AppTools toLogin];
            return;
        }
        if ([recent rangeOfString:@"pe://so.gui.de/classes"].location != NSNotFound) {
            //订单
            [AppTools getCurrentVC].tabBarController.selectedIndex = 1;
            return;
        }
        if ([recent rangeOfString:@"pe://so.gui.de/islove"].location != NSNotFound) {
            //产品详情
            NSArray *array = [recent componentsSeparatedByString:@"="];
            NSString *theId = [NSString stringWithFormat:@"%@",[array safeObjectAtIndex:1]];
            ProductDetailViewController *vc = [[ProductDetailViewController alloc] init];
            vc.productId = theId;
            vc.hidesBottomBarWhenPushed = YES;
            [[AppTools getCurrentVC].navigationController pushViewController:vc animated:YES];
            return;
        }
        
    }
}

#pragma mark - lazy load
- (BaseTableView *)tableView {
    if (!_tableView) {
        _tableView = [[BaseTableView alloc] initWithFrame:CGRectMake(0, kStarBarHeight, KScreenWidth, KScreenHeight-kStarBarHeight-kSafeBottomHeight-100) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = ColorHex(@"#FFFFFF");
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
